<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    const addWatermarkAndDownload = async (imageUrl, watermarkText, outputName) => {
        // 加载图片
        const image = new Image();
        image.crossOrigin = "anonymous";
        image.onload = () => {
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');

            // 设置Canvas大小
            canvas.width = image.width;
            canvas.height = image.height;

            // 绘制图片
            ctx.drawImage(image, 0, 0, canvas.width, canvas.height);

            // 添加水印（这里以文本为例）
            ctx.fillStyle = 'rgb(253,0,1)'; // 半透明白色
            console.log('canvas', canvas.width, canvas.height)
            ctx.font = `bold ${canvas.width / 6}px Arial`;
            ctx.fillText(watermarkText, 10, canvas.height - 10); // 在右下角添加水印

            // 将Canvas转换为Blob对象
            canvas.toBlob(blob => {
                // 创建一个指向Blob对象的URL
                const objectUrl = window.URL.createObjectURL(blob);

                // 创建下载链接并触发下载
                const a = document.createElement('a');
                a.href = objectUrl;

                //名称
                a.download = `${outputName}.${imageUrl.substring(imageUrl.lastIndexOf('.') + 1)}`; // 假设输出为PNG格式
                a.click();

                // 清理
                window.URL.revokeObjectURL(objectUrl);
                a.remove();
            }, 'image/png'); // 指定输出格式
        };
        image.src = imageUrl;
    };

    // 示例用法
    addWatermarkAndDownload('https://auto.hsdzipper.cn/minio-hsd-crm/2023/09/16/2ce95e8474aa464394b64bc7fd7402ea.jpg',
        'HSD', 'downloaded_image');
</script>
</body>
</html>
